<template>
  <div class="add-product">
    <div class="page-header">
      <h2>添加商品</h2>
      <router-link to="/shopkeeper/products" class="back-btn">
        返回商品列表
      </router-link>
    </div>
    
    <form @submit.prevent="handleSubmit" class="product-form">
      <div class="form-group">
        <label for="name">商品名称：</label>
        <input
          id="name"
          v-model="product.name"
          type="text"
          required
          placeholder="请输入商品名称"
        />
      </div>
      
      <div class="form-group">
        <label for="price">价格：</label>
        <input
          id="price"
          v-model.number="product.price"
          type="number"
          step="0.01"
          min="0"
          required
          placeholder="请输入价格"
        />
      </div>
      
      <div class="form-group">
        <label for="stock">库存：</label>
        <input
          id="stock"
          v-model.number="product.stock"
          type="number"
          min="0"
          required
          placeholder="请输入库存数量"
        />
      </div>
      
      <div class="form-group">
        <label for="category">分类：</label>
        <select id="category" v-model="product.category" required>
          <option value="">请选择分类</option>
          <option value="水果">水果</option>
          <option value="蔬菜">蔬菜</option>
          <option value="乳制品">乳制品</option>
          <option value="肉类">肉类</option>
          <option value="零食">零食</option>
          <option value="饮料">饮料</option>
          <option value="其他">其他</option>
        </select>
      </div>
      
      <div class="form-group">
        <label for="description">商品描述：</label>
        <textarea
          id="description"
          v-model="product.description"
          rows="4"
          required
          placeholder="请输入商品描述"
        ></textarea>
      </div>
      
      <div class="form-group">
        <label>商品图片：</label>
        <div class="image-upload-section">
          <div class="upload-area" @click="triggerFileInput" @drop="handleDrop" @dragover.prevent>
            <input
              ref="fileInput"
              type="file"
              accept="image/*"
              @change="handleFileSelect"
              style="display: none"
            />
            <div v-if="!previewImage" class="upload-placeholder">
              <span>📷 点击上传或拖拽图片</span>
              <small>支持 JPG、PNG、GIF 格式</small>
            </div>
            <img v-else :src="previewImage" alt="预览" class="preview-image" />
          </div>
          <div v-if="previewImage" class="image-actions">
            <button type="button" @click="removeImage" class="remove-btn">删除图片</button>
          </div>
        </div>
      </div>
      
      <div class="form-actions">
        <button type="submit" class="submit-btn" :disabled="loading">
          {{ loading ? '添加中...' : '添加商品' }}
        </button>
        <button type="button" @click="resetForm" class="reset-btn">
          重置
        </button>
      </div>
      
      <div v-if="error" class="error-message">{{ error }}</div>
    </form>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { useProductStore } from '../../stores/product'

const router = useRouter()
const productStore = useProductStore()

const loading = ref(false)
const error = ref('')
const fileInput = ref(null)
const previewImage = ref('')
const selectedFile = ref(null)

const product = reactive({
  name: '',
  price: 0,
  stock: 0,
  category: '',
  description: '',
  image: ''
})

const handleSubmit = async () => {
  loading.value = true
  error.value = ''
  
  try {
    // 处理图片
    if (selectedFile.value) {
      // 使用FileReader将图片转换为base64
      const reader = new FileReader()
      reader.onload = async (e) => {
        product.image = e.target.result
        await saveProduct()
      }
      reader.readAsDataURL(selectedFile.value)
    } else {
      // 如果没有选择图片，使用占位图片
      product.image = `https://via.placeholder.com/200x200/667eea/FFFFFF?text=${encodeURIComponent(product.name)}`
      await saveProduct()
    }
  } catch (err) {
    error.value = '添加商品失败：' + err.message
    loading.value = false
  }
}

const saveProduct = async () => {
  try {
    await productStore.createProduct(product)
    alert('商品添加成功！')
    router.push('/shopkeeper/products')
  } catch (err) {
    error.value = '添加商品失败：' + err.message
  } finally {
    loading.value = false
  }
}

const resetForm = () => {
  Object.assign(product, {
    name: '',
    price: 0,
    stock: 0,
    category: '',
    description: '',
    image: ''
  })
  previewImage.value = ''
  selectedFile.value = null
}

// 图片上传相关方法
const triggerFileInput = () => {
  fileInput.value.click()
}

const handleFileSelect = (event) => {
  const file = event.target.files[0]
  if (file) {
    processImageFile(file)
  }
}

const handleDrop = (event) => {
  event.preventDefault()
  const file = event.dataTransfer.files[0]
  if (file && file.type.startsWith('image/')) {
    processImageFile(file)
  }
}

const processImageFile = (file) => {
  if (!file.type.startsWith('image/')) {
    alert('请选择图片文件！')
    return
  }
  
  if (file.size > 5 * 1024 * 1024) {
    alert('图片大小不能超过5MB！')
    return
  }
  
  selectedFile.value = file
  const reader = new FileReader()
  reader.onload = (e) => {
    previewImage.value = e.target.result
  }
  reader.readAsDataURL(file)
}

const removeImage = () => {
  previewImage.value = ''
  selectedFile.value = null
  fileInput.value.value = ''
}
</script>

<style scoped>
.add-product {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #333;
}

.back-btn {
  padding: 8px 16px;
  background: #6c757d;
  color: white;
  text-decoration: none;
  border-radius: 4px;
  font-size: 14px;
  transition: background-color 0.3s;
}

.back-btn:hover {
  background: #5a6268;
}

.product-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
  max-width: 600px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-group label {
  font-weight: 500;
  color: #555;
  font-size: 14px;
}

.form-group input,
.form-group select,
.form-group textarea {
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 5px;
  font-size: 14px;
  transition: border-color 0.3s;
}

.form-group input:focus,
.form-group select:focus,
.form-group textarea:focus {
  outline: none;
  border-color: #667eea;
}

.form-group textarea {
  resize: vertical;
  min-height: 100px;
}

.form-actions {
  display: flex;
  gap: 15px;
  margin-top: 20px;
}

.submit-btn, .reset-btn {
  padding: 12px 24px;
  border: none;
  border-radius: 5px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.submit-btn {
  background: #667eea;
  color: white;
}

.submit-btn:hover:not(:disabled) {
  background: #5a6fd8;
}

.submit-btn:disabled {
  opacity: 0.7;
  cursor: not-allowed;
}

.reset-btn {
  background: #6c757d;
  color: white;
}

.reset-btn:hover {
  background: #5a6268;
}

.error-message {
  color: #e74c3c;
  font-size: 14px;
  margin-top: 10px;
}

/* 图片上传样式 */
.image-upload-section {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.upload-area {
  border: 2px dashed #ddd;
  border-radius: 8px;
  padding: 20px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s;
  min-height: 120px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.upload-area:hover {
  border-color: #667eea;
  background-color: #f8f9ff;
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  gap: 8px;
  color: #666;
}

.upload-placeholder span {
  font-size: 16px;
}

.upload-placeholder small {
  font-size: 12px;
  color: #999;
}

.preview-image {
  max-width: 100%;
  max-height: 200px;
  border-radius: 8px;
  object-fit: cover;
}

.image-actions {
  display: flex;
  justify-content: center;
}

.remove-btn {
  padding: 6px 12px;
  background: #ff4757;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 12px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.remove-btn:hover {
  background: #ff3742;
}
</style>